# from common.views.dictionary.drop_down_options import get_itme_value_list
from django.contrib.auth.decorators import permission_required
from tools.models.ttest_api_web_user import TTestApiWebUser
from django.shortcuts import HttpResponse
from django.shortcuts import render
import datetime
import json
# from django.contrib.auth.models import User


# 主页面视图
# @permission_required('tools.view_ttestapiwebuser')
def index(request):
    # 领域下拉选项
    # domain_select = get_itme_value_list('select_domain')
    domain_select = ['技术实验室', '调度排产', 'MES+']
    return render(request, 'webscan/data_collection_whitelist.html',{'obj_list': domain_select})


# 数据采集白名单查询服务
# @permission_required('tools.view_ttestapiwebuser')
def search_data_collection_whitelist(request):
    if request.method == 'GET':
        page_size = int(request.GET['pageSize'])
        page_number = int(request.GET['pageNumber'])

        # 查询条件处理
        domain = request.GET.get("domain").strip()
        operation_user = request.GET.get("operation_user").strip()
        operation_user_name = request.GET.get("operation_user_name").strip()
        position = request.GET.get("position").strip()

        conditionDic = {}
        if domain:
            conditionDic['domain'] = domain
        if operation_user:
            conditionDic['operation_user'] = operation_user
        if operation_user_name:
            conditionDic['operation_user_name'] = operation_user_name
        if position:
            conditionDic['position'] = position

        # 查询并分页
        total_list = TTestApiWebUser.objects.filter(**conditionDic).order_by('-last_update_date')
        print('conditionDic',conditionDic)
        print('total_list',total_list)
        configures = total_list[(page_number - 1) * page_size: page_number * page_size]
        total = len(total_list)

        # 构造返回数据
        rows = []
        for configure in configures:
            rows.append({
                'id': configure.id,
                'domain': configure.domain,
                'operation_user': configure.operation_user,
                'operation_user_name': configure.operation_user_name,
                'position': configure.position,
                'create_by': configure.create_by,
                'create_date': configure.create_date,
                'last_update_by': configure.last_update_by,
                'last_update_date': configure.last_update_date
            })

        data = {'total': total, 'rows': rows}
        return HttpResponse(json.dumps(data, cls=DateEncoder), content_type='application/json')


# 数据采集白名单新增服务
@permission_required('tools.add_ttestapiwebuser')
def insert_data_collection_whitelist(request):
    ctx = {}
    # user = User.objects.get(username=request.user.username)

    # 获取表单数据
    domain = request.POST['domain'].strip()
    operation_user = request.POST['operation_user'].strip()
    operation_user_name = request.POST['operation_user_name'].strip()
    position = request.POST['position'].strip()

    if request.POST:
        ctx['domain'] = domain
        ctx['operation_user'] = operation_user
        ctx['operation_user_name'] = operation_user_name
        ctx['position'] = position
        # ctx['create_by'] = str(user)
        # ctx['last_update_by'] = str(user)

    # 验证必填字段
    if domain == "" or operation_user == "" or operation_user_name == "" or position == "":
        data = {'ret': False, 'msg': '必填字段不能为空！'}
    # 检查账号是否已存在
    elif len(TTestApiWebUser.objects.filter(operation_user=operation_user).values()) > 0:
        data = {'ret': False, 'msg': '账号不能重复！'}
    else:
        TTestApiWebUser.objects.create(**ctx)
        data = {'ret': True, 'msg': '数据提交成功！'}

    return HttpResponse(json.dumps(data), content_type='application/json')


# # 数据采集白名单删除服务
# @permission_required('tools.delete_ttestapiwebuser')
# def delete_data_collection_whitelist(request):
#     # 获取要删除的ID列表
#     ids_list = request.POST.getlist('ids[]')
#
#     if len(ids_list) == 0:
#         data = {'ret': False, 'msg': '至少需要选中一条数据！'}
#         return HttpResponse(json.dumps(data), content_type='application/json')
#
#     # 执行删除操作
#     configure = TTestApiWebUser.objects.filter(id__in=ids_list)
#     configure.delete()
#     data = {'ret': True, 'msg': '删除成功！'}
#     return HttpResponse(json.dumps(data), content_type='application/json')
#
#
# # 获取需要更新的白名单数据
# @permission_required('tools.change_ttestapiwebuser')
# def search_data_collection_whitelist_byid(request):
#     id = request.POST['id']
#     configure = TTestApiWebUser.objects.get(pk=id)
#
#     data = {
#         'ret': True,
#         'data': {
#             'domain': configure.domain,
#             'operation_user': configure.operation_user,
#             'operation_user_name': configure.operation_user_name,
#             'position': configure.position,
#         }
#     }
#     return HttpResponse(json.dumps(data), content_type='application/json')
#
#
# # 更新白名单数据
# @permission_required('tools.change_ttestapiwebuser')
# def update_data_collection_whitelist(request):
#     # user = User.objects.get(username=request.user.username)
#     id = request.POST['id']
#     domain = request.POST['domain'].strip()
#     operation_user = request.POST['operation_user'].strip()
#     operation_user_name = request.POST['operation_user_name'].strip()
#     position = request.POST['position'].strip()
#
#     configure = TTestApiWebUser.objects.get(pk=id)
#
#     # 字段验证
#     if domain == "":
#         data = {'ret': False, 'msg': '领域不能为空！'}
#         return HttpResponse(json.dumps(data), content_type='application/json')
#     if operation_user == "":
#         data = {'ret': False, 'msg': '账号不能为空！'}
#         return HttpResponse(json.dumps(data), content_type='application/json')
#     if operation_user_name == "":
#         data = {'ret': False, 'msg': '姓名不能为空！'}
#         return HttpResponse(json.dumps(data), content_type='application/json')
#     if position == "":
#         data = {'ret': False, 'msg': '岗位不能为空！'}
#         return HttpResponse(json.dumps(data), content_type='application/json')
#
#     # 更新数据
#     configure.domain = domain
#     configure.operation_user = operation_user
#     configure.operation_user_name = operation_user_name
#     configure.position = position
#     # configure.last_update_by = str(user)
#     configure.save()
#
#     data = {'ret': True, 'msg': '修改成功！'}
#     return HttpResponse(json.dumps(data), content_type='application/json')

# 日期处理类
class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        return json.JSONEncoder.default(self, obj)